import logging
import tkinter as tk
from tkinter import messagebox, font

from utils.tools import read_json_file
from utils.logger import setup_logging
from login.net_login import net_get_request

# 获取日志器
setup_logging()
logger = logging.getLogger("GUI")


class LoginForm:
    def __init__(self, root):
        # 设置主窗口
        self.root = root
        self.root.title("校园网自动登录")
        self.root.geometry("330x300")
        self.root.resizable(False, False)

        # 确保中文显示正常
        self.custom_font = font.Font(family="SimHei", size=12)
        self.title_font = font.Font(family="SimHei", size=16, weight="bold")

        # 创建主框架
        self.main_frame = tk.Frame(root, padx=50, pady=30)
        self.main_frame.pack(fill=tk.BOTH, expand=True)

        # 添加标题
        self.title_label = tk.Label(
            self.main_frame,
            text="校园网自动登录",
            font=self.title_font
        )
        self.title_label.grid(row=0, column=0, columnspan=2, pady=20)

        # 用户名标签和输入框
        self.username_label = tk.Label(
            self.main_frame,
            text="学号:",
            font=self.custom_font
        )
        self.username_label.grid(row=1, column=0, sticky=tk.W, pady=10)

        self.username_var = tk.StringVar()
        self.username_entry = tk.Entry(
            self.main_frame,
            textvariable=self.username_var,
            font=self.custom_font,
            width=20
        )
        self.username_entry.grid(row=1, column=1, pady=10)
        self.username_entry.focus()  # 设置初始焦点

        # 密码标签和输入框
        self.password_label = tk.Label(
            self.main_frame,
            text="密码:",
            font=self.custom_font
        )
        self.password_label.grid(row=2, column=0, sticky=tk.W, pady=10)

        self.password_var = tk.StringVar()
        self.password_entry = tk.Entry(
            self.main_frame,
            textvariable=self.password_var,
            show="*",  # 密码显示为*
            font=self.custom_font,
            width=20
        )
        self.password_entry.grid(row=2, column=1, pady=10)

        # 按钮框架
        self.button_frame = tk.Frame(self.main_frame)
        self.button_frame.grid(row=3, column=0, columnspan=2, pady=20)

        # 登录按钮
        self.login_button = tk.Button(
            self.button_frame,
            text="登录",
            command=self.validate_login,
            font=self.custom_font,
            width=10,
            bg="#4CAF50",
            fg="white"
        )
        self.login_button.pack(side=tk.LEFT, padx=5)

        # 重置按钮
        self.reset_button = tk.Button(
            self.button_frame,
            text="重置",
            command=self.reset_form,
            font=self.custom_font,
            width=10,
            bg="#f44336",
            fg="white"
        )
        self.reset_button.pack(side=tk.RIGHT, padx=5)

        # 自动填充配置文件中的账户密码
        self.fill_credentials_from_config()

    def fill_credentials_from_config(self):
        """从配置文件填充账户密码"""
        config_data = read_json_file()
        print(config_data)
        if "params" in config_data:
            self.username_var.set(config_data["params"].get("DDDDD", ""))
            self.password_var.set(config_data["params"].get("upass", ""))

        # 设置初始焦点
        if not self.username_var.get():
            self.username_entry.focus()
        else:
            self.password_entry.focus()

    def validate_login(self):
        """验证登录信息"""
        username = self.username_var.get().strip()
        password = self.password_var.get().strip()
        logger.info("提交的账户：{},密码：{}".format(username, password))

        # 检查用户名是否为空
        if not username:
            messagebox.showerror("错误", "请输入用户名")
            self.username_entry.focus()
            return

        # 检查密码是否为空
        if not password:
            messagebox.showerror("错误", "请输入密码")
            self.password_entry.focus()
            return

        # 直接登录
        if net_get_request():
            # 4. 弹窗提醒（确认后关闭GUI）
            messagebox.showinfo("操作成功", f"欢迎回来，{username}！\n业务逻辑已执行完成，即将退出程序")
            # 5. 退出GUI（销毁主窗口）
            self.root.destroy()
        else:
            messagebox.showinfo("操作失败，请查看日志")

    def reset_form(self):
        """重置表单"""
        self.username_var.set("")
        self.password_var.set("")
        self.username_entry.focus()


if __name__ == "__main__":
    root = tk.Tk()
    app = LoginForm(root)
    root.mainloop()
